package repository

import (
	"rpc-service/user/datasource"
	"rpc-service/user/model"
	"sync"
)

/**
实现类
*/
type User struct {
}

/**
单例模式; 能避免同一对象被反复实例化
*/
var once sync.Once
var instance *User

func GetInstance() *User {
	once.Do(func() {
		instance = &User{}
	})
	return instance
}

// 传入接受结果集的变量只能是struct或者slice类型.
// 当传入sturct类型,检索出的结果为0条时,会抛出ErrRecordNotFound错误
// 当传入slice类型时,任何条件下都不会抛出ErrRecordNotFound错误

func (u *User) FindById(id int32) (*model.User, error) {
	user := &model.User{}
	user.ID = id
	if err := datasource.GetDB().First(user, id).Error; err != nil {
		return nil, err
	}
	return user, nil
}

func (u *User) FindByName(name string) ([]model.User, error) {
	user := make([]model.User,0,0)
	if err := datasource.GetDB().Where(model.User{UserName: name}).First(&user).Error; err != nil {
		return nil, err
	}
	return user, nil
}

func (u *User) Create(user *model.User) (*model.User, error) {
	if err := datasource.GetDB().Create(user).Error; err != nil {
		return nil, err
	}
	return user, nil
}

func (u *User) Update(user *model.User) (*model.User, error) {
	if err := datasource.GetDB().Update(user).Error; err != nil {
		return nil, err
	}
	return user, nil
}
